<template>
    <div>
         <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区 -->
    <el-card>
         <el-button type="primary" @click="dialogVisible = true"
            >添加角色</el-button
          >
        <!-- 权限列表 -->
        <el-table border stripe :data="rolesList" style="width: 100%">
            <!-- 展开列 -->
            <el-table-column type="expand"> 
              <template slot-scope="scope">
               <el-row :class="['bdbottom',i1 ===0?'bdtop':'','vcenter']" v-for="(item1,i1) in scope.row.children" :key="item1.id">
                 <!-- 一级权限 -->
                 <el-col :span="5">
                   <el-tag closable @close="removeRightByid(scope.row,item1.id)">{{item1.authName}}</el-tag>
                   <i class="el-icon-caret-right"></i>
                 </el-col>
                 <!-- 二级跟三级权限 -->
                   <el-col :span="19">
                     <!-- 通过for循环渲染二级权限 -->
                     <el-row :class="[i2 ===0?'':'bdtop','vcenter']" v-for="(item2,i2) in item1.children" :key="item2.id">
                       <el-col :span="6">
                         <el-tag  closable @close="removeRightByid(scope.row,item2.id)" type="success">{{item2.authName}}</el-tag>
                         <i class="el-icon-caret-right"></i>
                       </el-col>
                       <el-col :span="18">
                         <el-tag closable @close="removeRightByid(scope.row,item3.id)" type="warning" v-for="(item3,i3) in item2.children" :key="item3.id">
                           {{item3.authName}}
                         </el-tag>
                       </el-col>
                     </el-row>
                   </el-col>
               </el-row>
              </template>
            </el-table-column>
        
        <el-table-column label="#" type="index"> </el-table-column>
        <el-table-column prop="roleName" label="角色" >
        </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述" >
        </el-table-column>
        <el-table-column prop="level" label="操作"> 
            <template slot-scope="scope">
                <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditDialog(scope.row.id)"
            >编辑</el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
            @click="open(scope.row.id)"
            >删除</el-button>
           
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="showSetRig(scope.row)"
              >分配权限</el-button>
            </template>
        </el-table-column>
      
      </el-table>
    </el-card>

     <!-- 添加角色对话框 -->
    <el-dialog title="添加用户" :visible.sync="dialogVisible" width="50%"
    @close="addDialogClosed">
      <!-- 内容主题区 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser"
          >确 定</el-button
        >
      </span>
    </el-dialog>

      <!-- 编辑角色对话框 -->
    <el-dialog title="修改角色信息" :visible.sync="dialogVisible1" width="50%"
    @close="editDialogClosed">
      <!-- 内容主题区 -->
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible1 = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <!-- 分配权限的对话框 -->
    <el-dialog
  title="分配权限"
  :visible.sync="setRightDialog"
  width="50%"
  @close="setRightDialogCloser"
  >
  <!-- 树形控件 -->
  <el-tree default-expand-all :default-checked-keys="defKeys" show-checkbox node-key="id"
   :data="rightslist" :props="treeProps" 
  ref="treeRef"></el-tree>
  <span slot="footer" class="dialog-footer">
    <el-button @click="setRightDialog = false">取 消</el-button>
    <el-button type="primary" @click="allotRights">确 定</el-button>
  </span>
</el-dialog>

    </div>
</template>
<script>

export default {
    data(){
        return {
          //当前即将分配权限的Id
          roleId:'',
          //树形控件默认选中的节点Id值的数组
          defKeys:[],
            //树形控件的属性绑定对象
         treeProps:{
           label:'authName',
           children:'children'
         },
             //编辑角色对象
      editForm:{},
            //权限列表
            rolesList:[],
            rightslist:[],
            dialogVisible:false,
            dialogVisible1:false,
             //添加角色表单
      addForm:{
        roleName:'',
        roleDesc:'',
      },
         //添加角色表单规则对象
      addFormRules:{
        roleName:[
           { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 2,
            max: 10,
            message: "长度在 2 到 10 个字符",
            trigger: "blur",
          },
        ],
        roleDesc: [
          { required: true, message: "请输入登录密码", trigger: "blur" },
          {
            min: 3,
            max: 50,
            message: "长度在 3 到 50 个字符",
            trigger: "blur",
          },
        ],
      },
       //修改角色表单规则对象
       editFormRules:{
         roleName:[
           { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 2,
            max: 10,
            message: "长度在 2 到 10 个字符",
            trigger: "blur",
          },
        ],
        roleDesc: [
          { required: true, message: "请输入登录密码", trigger: "blur" },
          {
            min: 3,
            max: 50,
            message: "长度在 3 到 50 个字符",
            trigger: "blur",
          },
        ],
       },
         setRightDialog:false,
        }
    },
    created(){
        this.getRolesList();
    },
    methods:{
        async getRolesList(){
          const {data:res} =  await this.$http.get('roles')
          if (res.meta.status !== 200) {
        return this.$message.error("获取角色列表失败！");
      }
      this.rolesList = res.data
      console.log(res.data);
        },
         //关闭添加角色对话框重置
    addDialogClosed(){
      this.$refs.addFormRef.resetFields();
    },
        //添加角色确定按钮事件
   async addUser(){
      this.$refs.addFormRef.validate(value=>{
        if(!value)return;
        //通过预校验则发起添加用户请求
      })
       const {data:res} = await this.$http.post('roles',this.addForm)
        if(res.meta.status !== 201) return this.$message.error(res.meta.msg);
       this.$message.success('添加角色成功');
       //隐藏对话框
        this.dialogVisible = false;
        //重新获取用户列表数据
        this.getRolesList();
    },
     //展示编辑角色对话框
    async showEditDialog(id){
      console.log(id);
      const {data:res} = await this.$http.get('roles/'+ id)
         if(res.meta.status !== 200){
           return this.$message.error(res.meta.msg);
         } 
        this.editForm = res.data
        console.log(res.data);
      this.dialogVisible1 = true
    },

      editUserInfo(){
      this.$refs.editFormRef.validate(async value=>{
        if(!value)return;
        //通过预校验则发起修改用户请求
         const {data:res} = await this.$http.put('roles/'+this.editForm.roleId,{
           roleName:this.editForm.roleName,
           roleDesc:this.editForm.roleDesc,
         })
        if(res.meta.status !== 200) return this.$message.error(res.meta.msg);
       
       //关闭对话框
      this.dialogVisible1 = false;
      //刷新数据列表
      this.getRolesList();
      this.$message.success('修改成功');
      })
      
    },

      //监听角色修改资料对话框的关闭事件
    editDialogClosed(){
       this.$refs.editFormRef.resetFields();
    },

    //删除角色提示
      open(id) {
        this.$confirm('此操作将永久该角色, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
         const{data:res} = await this.$http.delete('roles/'+id)
          if(res.meta.status !== 200) {return this.$message.error(res.meta.msg)};
         console.log(res);
         //重新获取用户列表数据
         this.getRolesList();
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
      },
      //根据id删除角色权限
      removeRightByid(reol,rightId){
        //弹窗提示用户是否要删除
        this.$confirm('此操作将永久该权限, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
         const{data:res} = await this.$http.delete(`roles/${reol.id}/rights/${rightId}`)
          if(res.meta.status !== 200) {return this.$message.error(res.meta.msg)};
         console.log(res);
         //会重新获取整个权限列表数据 (不建议)
        //  this.getRolesList();
        //只会改动角色权限  （建议）
        reol.children = res.data
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
      },
        //展示分配权限的对话框
        async showSetRig(reol){
          this.roleId = reol.id
        //获取所有权限的数据
          const {data:res} =  await this.$http.get('rights/tree')
          if (res.meta.status !== 200) {
        return this.$message.error("获取角色列表失败！");
      }
      this.rightslist = res.data
      console.log(res.data);
        //递归获取三级节点的Id
        this.getLeafKeys(reol,this.defKeys);

        this.setRightDialog = true
      },
      //通过递归的形式，获取角色下所有三级权限id，并保存到 defKeys 数组中
      getLeafKeys(node,arr){
        //如果当前node节点不包含 children 属性 ，则是三级节点
        if (!node.children) {
          return arr.push(node.id)
        }
          //不是三级节点，则递归获取到三级节点
          node.children.forEach(item => {
            this.getLeafKeys(item,arr)
          });
      },

      //关闭编辑权限对话框 重置清空 defKeys 数组
      setRightDialogCloser(){
        this.defKeys = [];
      },
      //点击确定为角色分配权限
     async allotRights(){
        const keys = [
          ...this.$refs.treeRef.getCheckedKeys(),
          ...this.$refs.treeRef.getHalfCheckedKeys()
        ]
        const idStr = keys.join(',')
      const {data:res}=  await  this.$http.post(`roles/${this.roleId}/rights`,{rids:idStr})
         if(res.meta.status !== 200) {return this.$message.error(res.meta.msg)};
         this.$message.success('分配权限成功')
         this.getRolesList();
         this.setRightDialog = false
      },
    },
}
</script>
<style lang="scss" scoped>
.el-tag{
  margin: 7px;
}
.bdtop{
  border-top: 1px solid #eee;
}
.bdbottom{
border-bottom: 1px solid #eee;
}
.vcenter{
  display: flex;
  align-items: center;
}
</style>
